package com.db.patterns.transport.client;

import com.db.patterns.transport.listener.TransportListener;

import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @author nulls.narik
 */
public abstract class AbstractClientTransport implements ClientTransport {

    @Override
    public abstract Object getMessage();

    @Override
    public abstract void sendMessage(Object message);

    private final Set<TransportListener> listeners = new CopyOnWriteArraySet<TransportListener>();

    public void addListener(TransportListener listener) {
        listeners.add(listener);
    }

    public void removeListener(TransportListener listener) {
        listeners.remove(listener);
    }

    private volatile boolean isStopReceiveNewMessage = false;

    private final Thread receiveNewMessages = new Thread(new Runnable() {
        @Override
        public void run() {
            while (!isStopReceiveNewMessage) {
                Object message = getMessage();
                for (TransportListener listener : listeners) {
                    listener.newMessage(message);
                }
            }
        }
    });

    public void startReceiveNewMessage() {
        isStopReceiveNewMessage = true;
        receiveNewMessages.start();
    }

    public void stopReceiveNewMessage() {
        isStopReceiveNewMessage = true;
    }

}
